<?php

/*e
 * This is the model class for table "{{users}}".
 *
 * The followings are the available columns in table '{{users}}':
 * @property integer $id
 * @property string $username
 * @property string $domain
 * @property string $realname
 * @property string $password
 * @property integer $email
 * @property integer $role
 * @property integer $status
 * @property string $lastedit
 * @property string $lastlogin
 */
class Users extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Users the static model class
	 */
    public $id;
    public $username;
    public $password;
    public $domain;
    public $realname;
    public $email;
    public $role = self::ROLE_USER;
    public $status;
    public $lastedit;
    public $lastlogin;

    const ROLE_USER = 1;
    const ROLE_ADMIN = 2;
    const STATUS_AVAILABLE = 1;
    const STATUS_DISABLE = 2;

	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{users}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username, realname, password', 'required'),
			array('role, status', 'numerical', 'integerOnly'=>true),
			array('username', 'length', 'max'=>50),
			array('domain', 'length', 'max'=>30),
			array('realname', 'length', 'max'=>20),
			array('email', 'length', 'max'=>100),
			array('password', 'length', 'max'=>200),
			array('lastedit, lastlogin', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, username, domain, realname, password, email, role, status, lastedit, lastlogin', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
            /*
			'id' => 'ID',
			'username' => 'Username',
			'domain' => 'Domain',
			'realname' => 'Realname',
			'password' => 'Password',
			'email' => 'Email',
			'role' => 'Role',
			'status' => 'Status',
			'lastedit' => 'Lastedit',
			'lastlogin' => 'Lastlogin',
            */

			'id' => 'ID',
			'username' => '用户名',
			'domain' => '域',
			'realname' => '花名',
			'password' => '密码',
			'email' => 'Mail',
			'role' => '角色',
			'status' => '状态',
			'lastedit' => '最近更新',
			'lastlogin' => '上次登录',
            
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

        if(isset($this->role) && $this->role!='' && $this->role != Null)
        {
            $role = CActiveRecord::model('Role')->find('rolename=\''.$this->role.'\'');
            if($role != Null)
                $this->role = $role->id;
        }
        if(isset($this->status) && $this->status!='' && $this->status != Null)
        {
            $status = CActiveRecord::model('Status')->find('statusname=\''.$this->status.'\'');
            if($status != Null)
                $this->status = $status->id;
        }

		$criteria->compare('id',$this->id);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('domain',$this->domain,true);
		$criteria->compare('realname',$this->realname,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('email',$this->email);
		$criteria->compare('role',$this->role);
		$criteria->compare('status',$this->status);
		$criteria->compare('lastedit',$this->lastedit,true);
		$criteria->compare('lastlogin',$this->lastlogin,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

    /**
     * before validate
     * 在验证前的操作
     *
     * 如果是新记录
     * 1.将lastedit lastlogin设置为当前时间
     * 2.将usermame全小写
     * 3.根据username, domain判断用户是否已经存在
     * 4.根据username, domain通过LDAP查询用户信息
     * 否则
     * 1.将lastedit设置为当前时间
     */
    protected function beforeValidate()
    {
        if($this->isNewRecord)
        {
            $this->lastedit = $this->lastlogin = date(Yii::app()->params->dateFormat);
            $this->username = strtolower($this->username);
            $user = Users::model()->findByAttributes(array(
                'username' => $this->username,
                'domain' => $this->domain
            ));
            if($user !== null)
            {
                $this->addError('username', Yii::t('User', 'Username has been exists.'));
                return false;
            }
            $ldapConfig = Yii::app()->params['ldap'];
            $ldap = new Ldap($ldapConfig['user'], $ldapConfig['pass']);
            $userInfo = $ldap->search($this->domain, $this->username);

            if(empty($userInfo))
            {
                $this->addError('username', Yii::t('User', 'Domain username not exists.'));
                return false;
            }
            else
            {
                $this->realname = $userInfo->realname;
                $this->email = $userInfo->email;
            }
        }
        else
        {
            $this->lastedit = date(Yii::app()->params->dateFormat);
        }
        //Yii::log('amazing','info', 'ts.admin.debug');
        return true;
    }

}
